/**
 *  Eclipse Public License 1.0
 */
package org.fireblade.easysms;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.util.Log;

/**
 * simple service. should be improved to run more stable/longer and not killed so often by android @Todo
 */
public class Wifi_USBService extends AbstractService {
  /**
   * own log tag
   */
  private static final String LOGTAG = MainActivity.EASY_SMS + Wifi_USBService.class.getSimpleName();

  /** the thread of the http server */
  static Thread thread = null;
  /** the server itself */
  static Wifi_USBServer server = null;
  /** if started by usb / usb known as connected */
  static boolean usb = false;
  /** if started by wifi / wifi known as online */
  static boolean wifi = false;
  /** if wifi has been locked */
  static WifiManager.WifiLock wifiLock = null;

  /**
   * cpu wake lock
   */
  static PowerManager.WakeLock wakeLock;


  @Override
  public void onCreate() {
    super.onCreate();
    Log.d(LOGTAG, "Service created.");
  }


  /*
   * (non-Javadoc)
   * @see org.fireblade.easysms.AbstractService#getNotificationId()
   */
  @Override
  protected int getNotificationId() {
    return 1;
  }


  /*
   * (non-Javadoc)
   * @see org.fireblade.easysms.AbstractService#getConnectionType()
   */
  @Override
  protected String getConnectionType() {
    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    String ipAddress = "";
    return "Wifi/USB" + ipAddress;
  }


  boolean isRunning() {
    return null != server && !server.hasStopped && !server.shouldStop;
  }


  void startServer() {
    Log.i(LOGTAG, "startServer");
    setForeground();
    SharedPreferences pref = getSharedPreferences(MainActivity.EASY_SMS_SP, Context.MODE_PRIVATE);
    boolean keepWifi = pref.getBoolean(MainActivity.KEEP_WIFI, true);

    server = new Wifi_USBServer();
    server.serviceInstance = this;
    thread = new Thread(server);
    thread.start();
    Log.i(LOGTAG, "startServer done");
    // Toast.makeText(this, "Server START", Toast.LENGTH_SHORT).show();
  }


  void stopServer() {
    try {
      if (null != server) {
        while (!server.hasStopped) {
          try {
            Log.d(LOGTAG, "Wait for server death");
            Thread.sleep(100);
          } catch (InterruptedException e) {
            Log.w(LOGTAG, "Could not wait for server death", e);
          }
        }
        server = null;
      }

      Log.i(LOGTAG, "stopServer done");
      // Toast.makeText(this, "Server STOP", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
      Log.e(LOGTAG, "unexepcted exception", e);
      throw new RuntimeException(e);
    } finally {
      stopSelf();
    }
  }


  /*
   * (non-Javadoc)
   * @see android.app.Service#onStart(android.content.Intent, int)
   */
  @Override
  public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Log.d(LOGTAG, "onStart: " + intent);
    String action = intent.getStringExtra(Wifi_USBEventReceiver.ACTION);
    Log.d(LOGTAG, Wifi_USBEventReceiver.ACTION + "=" + action);

    if (action.equals(Wifi_USBEventReceiver.MANUAL_OFF)) {
      if (isRunning()) {
        Log.d(LOGTAG, "manual off");
        stopServer();
      } else {
        Log.d(LOGTAG, "already stopped");
      }
      stopSelf();
      return;
    }
    if (action.equals(Wifi_USBEventReceiver.MANUAL_ON)) {
      if (!isRunning()) {
        Log.d(LOGTAG, "manual on");
        startServer();
      } else {
        Log.d(LOGTAG, "already running");
      }
      return;
    }


    // Toast.makeText(this, "Wifi: " + wifi + "/USB " + usb, Toast.LENGTH_SHORT).show();
  }


  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(LOGTAG, "onDestroy");
    if (null != wakeLock) {
      wakeLock.release();
      Log.d(LOGTAG, "Released wake lock");
    }
    Log.i(LOGTAG, "onDestroy called.");
    if (null != server) {
      server.shouldStop = true;
      server = null;
    }
    if (null != thread) {
      thread.interrupt();
      thread = null;
      Log.i(LOGTAG, "Interrupted server.");
    }
  }
}
